package com.whfc.emp.manager.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.exception.BizException;
import com.whfc.common.face.wheatSunshine.AuthorizationQueryResult;
import com.whfc.common.face.wheatSunshine.FaceResult;
import com.whfc.common.face.wheatSunshine.WheatSunshineConst;
import com.whfc.common.face.wheatSunshine.WheatSunshineFaceApi;
import com.whfc.common.geometry.Point;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.third.map.MapApi;
import com.whfc.common.third.map.MapLoc;
import com.whfc.common.util.Base64Util;
import com.whfc.emp.dao.AppEmpMapper;
import com.whfc.emp.dao.AppFaceGateFaceMapper;
import com.whfc.emp.dao.AppFaceGateMapper;
import com.whfc.emp.dao.AppFaceGatePersonMapper;
import com.whfc.emp.entity.*;
import com.whfc.emp.enums.FaceGateType;
import com.whfc.emp.enums.TaskType;
import com.whfc.emp.manager.FaceGateManager;
import com.whfc.emp.param.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sun_guodong
 * @description
 * @date 2020-06-20
 */
@Service("wheatSunshineFaceGateManagerImpl")
public class WheatSunshineFaceGateManagerImpl implements FaceGateManager {

    private static final Logger logger = LoggerFactory.getLogger(WheatSunshineFaceGateManagerImpl.class);

    @Autowired
    private AppEmpMapper appEmpMapper;

    @Autowired
    private AppFaceGateMapper appFaceGateMapper;

    @Autowired
    private AppFaceGatePersonMapper appFaceGatePersonMapper;

    @Autowired
    private AppFaceGateFaceMapper appFaceGateFaceMapper;

    @Autowired
    private MapApi mapApi;

    private WheatSunshineFaceApi wheatSunshineFaceApi;

    /**
     * 成功
     */
    private final static String SUCCESS = "1000";

    /**
     * 设备已存在
     */
    private final static String EXISTING = "1104";


    @Override
    public void info(AppFaceGateConfig appFaceGateConfig) {
        String appId = appFaceGateConfig.getAppId();
        String appSecret = appFaceGateConfig.getAppSecret();
        wheatSunshineFaceApi = new WheatSunshineFaceApi(appId, appSecret, WheatSunshineConst.server);
    }

    @Override
    public void add(AppFaceGateAddParam request) {
        String deviceKey = request.getDeviceKey();
        Integer deptId = request.getDeptId();
        String name = request.getName();
        Point point = request.getPoint();

        AppFaceGate appFaceGate = appFaceGateMapper.selectByDeviceKey(deviceKey);
        if (appFaceGate != null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该闸机已存在，不能重复添加！");
        }

        FaceResult<String> faceResult = wheatSunshineFaceApi.deviceAdd(deviceKey, name);

        if (EXISTING.equals(faceResult.getCode())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "设备已存在");
        }

        if (SUCCESS.equals(faceResult.getCode())) {
            AppFaceGate record = new AppFaceGate();
            record.setDeptId(deptId);
            record.setName(name);
            record.setDirection(request.getDirection());
            record.setDeviceKey(deviceKey);
            record.setPlatform(FaceGateType.WHEATSUNSHINE.getCode());
            // 增加闸机位置信息
            if (point != null) {
                Double lat = point.getLat();
                Double lng = point.getLng();
                MapLoc loc = mapApi.geocode(lng, lat);
                record.setLat(lat);
                record.setLng(lng);
                record.setAddress(loc.getAddress());
            }
            appFaceGateMapper.insertSelective(record);
        }

    }

    @Override
    public void del(Integer faceGateId) {
        AppFaceGate faceGate = appFaceGateMapper.selectByPrimaryKey(faceGateId);
        if (faceGate == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "WheatSunshineApi////该闸机不存在");
        }
        Integer count = appFaceGatePersonMapper.countByFaceGateId(faceGateId);
        if (count > 0) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "WheatSunshineApi////该闸机下还有人员未销权，不能删除！");
        }
        FaceResult<String> result = wheatSunshineFaceApi.deviceDel(faceGate.getDeviceKey());
        if (SUCCESS.equals(result.getCode())) {
            //成功
            appFaceGateMapper.deleteLogicById(faceGateId);
        }
    }

    @Override
    public String faceGateGrantEmdAdd(FaceGateGrantEmdAddParam request) {
        Integer empId = request.getEmpId();
        Integer personId = request.getPersonId();
        AppEmp appPerson = appEmpMapper.selectByPrimaryKey(empId);
        String name = appPerson.getEmpName();
        // 人员注册
        FaceResult result = wheatSunshineFaceApi.personAdd(name);
        if (SUCCESS.equals(result.getCode())) {
            //人员注册成功
            String data = JSONObject.toJSONString(result.getData());
            String personGuid = JSON.parseObject(data).getString("guid");
            appFaceGatePersonMapper.updateGrantInfo(personId, TaskType.EMP_ADD.getValue(), personGuid);
            return personGuid;
        } else {
            logger.info("人员注册失败,name:{},code:{},message:{}", name, result.getCode(), result.getMsg());
            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_ADD_ERROR.getValue(), "人员注册失败");
            return null;
        }
    }

    @Override
    public String faceGateGrantEmdImgAdd(FaceGateGrantEmdImgAddParam request) {
        Integer personId = request.getPersonId();
        String personGuid = request.getPersonGuid();
        String imgUrl = request.getImgUrl();
        // 照片注册
        FaceResult faceResult = wheatSunshineFaceApi.personFaceAdd(personGuid, Base64Util.getUrlImageToBase64(imgUrl));
        // 照片注册接口调用成功
        if (SUCCESS.equals(faceResult.getCode())) {
            AppFaceGatePerson appFaceGatePerson = appFaceGatePersonMapper.selectByPrimaryKey(personId);

            String faceResultData = JSONObject.toJSONString(faceResult.getData());
            JSONObject jsonObject = JSON.parseObject(faceResultData);
            String faceGuid = jsonObject.getString("pictureId");
            String faceUrl = jsonObject.getString("pictureUrl");

            AppFaceGateFace appFaceGateFace = new AppFaceGateFace();
            appFaceGateFace.setDeptId(appFaceGatePerson.getDeptId());
            appFaceGateFace.setDeviceKey(appFaceGatePerson.getDeviceKey());
            appFaceGateFace.setEmpId(appFaceGatePerson.getEmpId());
            appFaceGateFace.setFaceGateId(appFaceGatePerson.getFaceGateId());
            appFaceGateFace.setFaceGuid(faceGuid);
            appFaceGateFace.setFaceUrl(faceUrl);
            appFaceGateFace.setPersonGuid(personGuid);
            appFaceGateFaceMapper.insertSelective(appFaceGateFace);

            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_IMG_ADD.getValue(), "照片注册成功");
            return personGuid;
        } else {
            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_IMG_ADD_ERROR.getValue(), "照片注册失败");
            return null;
        }
    }

    @Override
    public String faceGateGrantEmdAuth(FaceGateGrantEmdAuthParam request) {
        String deviceKey = request.getDeviceKey();
        String personGuid = request.getPersonGuid();
        Integer personId = request.getPersonId();
        FaceResult stringFaceResult = wheatSunshineFaceApi.deviceAuthorization(deviceKey, Arrays.asList(personGuid));
        if (SUCCESS.equals(stringFaceResult.getCode())) {
            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_AUTH.getValue(), "人员授权成功");
            return personGuid;
        } else {
            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_AUTH_ERROR.getValue(), "人员授权失败");
            return null;
        }
    }

    @Override
    public void faceGateBatchGrantEmpAuth(AppFaceGateGrantEmpParam request) {

    }

    @Override
    public void faceGateRevokeEmp(AppFaceGateGrantEmpParam request) {
        Integer faceGateId = request.getFaceGateId();
        List<Integer> empIdList = request.getEmpIdList();

        AppFaceGate faceGate = appFaceGateMapper.selectByPrimaryKey(faceGateId);
        if (faceGate == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该闸机不存在");
        }
        List<String> personGuidList = new ArrayList<>();
        for (Integer empId : empIdList) {
            List<String> personGuid = appFaceGatePersonMapper.selectPersonGuidByFaceGateIdAndEmpId(faceGateId, empId);
            if (personGuid != null && personGuid.size() > 0) {
                personGuidList.addAll(personGuid);
            }
        }
        if (!personGuidList.isEmpty()) {
            FaceResult<String> faceResult = wheatSunshineFaceApi.deviceAuthorizationCancel(faceGate.getDeviceKey(), personGuidList);
            if (SUCCESS.equals(faceResult.getCode())) {
                //成功
                appFaceGatePersonMapper.delBYDeviceKeyAndParsonGuid(faceGate.getDeviceKey(), personGuidList);
            }
        }

    }

    @Override
    public String deviceAuthorizationPerson(String deviceKey, String name, String imgUrl) {
        // 人员注册
        FaceResult result = wheatSunshineFaceApi.personAdd(name);
        if (SUCCESS.equals(result.getCode())) {
            //人员注册成功
            String data = JSONObject.toJSONString(result.getData());
            String personGuid = JSON.parseObject(data).getString("guid");
            // 照片注册
            FaceResult faceResult = wheatSunshineFaceApi.personFaceAdd(personGuid, Base64Util.getUrlImageToBase64(imgUrl));
            // 照片注册接口调用成功
            if (SUCCESS.equals(faceResult.getCode())) {
                FaceResult stringFaceResult = wheatSunshineFaceApi.deviceAuthorization(deviceKey, Collections.singletonList(personGuid));
                if (SUCCESS.equals(stringFaceResult.getCode())) {
                    return personGuid;
                }
            }
        }
        throw new BizException(ResultEnum.FAILURE.getCode(), "人员授权失败");
    }

    @Override
    public String deviceAuthorizationCancel(String deviceKey, String personGuid) {
        String result = "";
        FaceResult<String> faceResult = wheatSunshineFaceApi.deviceAuthorizationCancel(deviceKey, personGuid);
        if (faceResult != null) {
            result = faceResult.getCode();
        }
        return result;
    }

    @Override
    public void openDoor(String deviceKey) {
        FaceResult<String> faceResult = wheatSunshineFaceApi.deviceOpenDoor(deviceKey);
        if (!SUCCESS.equals(faceResult.getCode())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "闸机开门失败");
        }
    }

    @Override
    public void sync(Integer faceGateId) {
        AppFaceGate faceGate = appFaceGateMapper.selectByPrimaryKey(faceGateId);
        if (faceGate == null) {
            return;
        }
        String deviceKey = faceGate.getDeviceKey();
        FaceResult<String> faceResult = wheatSunshineFaceApi.deviceAuthorizationQuery(deviceKey);
        List<AuthorizationQueryResult> results = JSON.parseArray(faceResult.getData(), AuthorizationQueryResult.class);

        //闸机平台授权成功personGuid列表
        List<String> guidList = results.stream().map(ret -> ret.getGuid()).collect(Collectors.toList());

        //本系统授权的personGuid列表
        List<String> allGuidList = appFaceGatePersonMapper.selectPersonGuidByFaceGateId(faceGateId);
        allGuidList.removeAll(guidList);
        if (allGuidList.size() > 0) {
            //todo 清理闸机平台中授权失败的信息
        }
    }

    @Override
    public String getToken() {
        return null;
    }
}
